package com.xml.dom.write;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLMaker {

	private Document doc;

	/**
	 * Constructor of XMLMaker
	 * 
	 * @param list
	 *            List
	 * @throws ParserConfigurationException
	 */
	public XMLMaker(List<Map<String, String>> list)
			throws ParserConfigurationException {
		this.createDocument(list);
	}

	/**
	 * Writing XML file
	 * 
	 * @param name
	 *            String
	 * @throws TransformerFactoryConfigurationError
	 * @throws TransformerException
	 * @throws IOException
	 */
	public void makeFile(String name)
			throws TransformerFactoryConfigurationError, TransformerException,
			IOException {
		Transformer trans = TransformerFactory.newInstance().newTransformer();
		trans.transform(new DOMSource(doc), new StreamResult(new FileWriter(
				name)));
	}

	/**
	 * setting member Document from Argument list
	 * 
	 * @param list
	 *            List
	 * @throws ParserConfigurationException
	 */
	private void createDocument(List<Map<String, String>> list)
			throws ParserConfigurationException {
		if (null != list && list.size() > 0) {
			doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.newDocument();
			Element books = doc.createElement("books");
			doc.appendChild(books);
			for (Map<String, String> map : list) {
				books.appendChild(getElement(map));
			}
		}
	}

	/**
	 * getting Element from Map
	 * 
	 * @param map
	 *            Map
	 * @return Element
	 */
	private Element getElement(Map<String, String> map) {
		Element book = null;
		if (null != doc && null != map) {
			book = doc.createElement("book");
			Iterator<String> keys = map.keySet().iterator();
			while (keys.hasNext()) {
				String key = keys.next();
				Element ele = doc.createElement(key);
				ele.setTextContent(map.get(key));
				book.appendChild(ele);
			}
		}
		return book;
	}

}
